﻿#include "FITKAcousticsVTKColorMapPartManager.h"

// VTK
#include <vtkUnstructuredGrid.h>

// Color map
#include "FITKAcousticsVTKColorMap.h"

// Global data
#include "FITK_Kernel/FITKCore/FITKDataRepo.h"

// Data
#include "FITK_Component/FITKAbaqusData/FITKAbaqusPart.h"
#include "FITK_Interface/FITKInterfaceStructural/FITKAbaMeshPartVTK.h"

namespace Exchange
{
    // Inistailize the static instance.
    FITKAcousticsVTKColorMapPartManager* FITKAcousticsVTKColorMapPartManager::s_instance{ nullptr };

    FITKAcousticsVTKColorMapPartManager* FITKAcousticsVTKColorMapPartManager::getInstance()
    {
        if (!s_instance)
        {
            s_instance = new FITKAcousticsVTKColorMapPartManager;
        }

        return s_instance;
    }

    void FITKAcousticsVTKColorMapPartManager::Destory()
    {
        if (s_instance)
        {
            delete s_instance;
        }

        s_instance = nullptr;
    }

    FITKAcousticsVTKColorMapPartManager::~FITKAcousticsVTKColorMapPartManager()
    {
        // Delete all color map.
        for (FITKAcousticsVTKColorMap* obj : m_partColorMapHash.values())
        {
            if (obj)
            {
                delete obj;
            }
        }

        m_partColorMapHash.clear();
    }

    FITKAcousticsVTKColorMap* FITKAcousticsVTKColorMapPartManager::getPartColorMap(int partId)
    {
        if (m_partColorMapHash.contains(partId))
        {
            return m_partColorMapHash[partId];
        }
        else
        {
            // Get the part data.
            AbaqusData::FITKAbaqusPart* part = Core::FITKDataRepo::getInstance()->getTDataByID<AbaqusData::FITKAbaqusPart>(partId);
            if (!part)
            {
                return nullptr;
            }

            // Get mesh data from the part data.
            Interface::FITKAbaMeshPartVTK* meshData = part->getMesh();
            if (!meshData)
            {
                return nullptr;
            }

            // Initialize the color map and its input dataset.
            FITKAcousticsVTKColorMap* colorMap = new FITKAcousticsVTKColorMap;
            colorMap->setInputData(meshData->getGrid());

            // Delete the color automaticly while the part has been deleted.
            //@{
            connect(part, &AbaqusData::FITKAbaqusPart::dataObjectDestoried, this, [=]
            {
                FITKAcousticsVTKColorMap* obj = m_partColorMapHash.take(partId);
                if (obj)
                {
                    delete obj;
                }
            });
            //@}

            // Add to the dict.
            m_partColorMapHash.insert(partId, colorMap);

            return colorMap;
        }
    }
}